package com.winit.openapi.tools.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.v2.WinitProductRecommendService;
import com.winit.oms.spi.v2.tools.command.BatchEGDValidateCommand;
import com.winit.oms.spi.v2.tools.command.ProductRecommendCommand;
import com.winit.oms.spi.v2.tools.request.ProductRecommendRequestParams;
import com.winit.oms.spi.v2.tools.result.ProductRecommendProductResult;
import com.winit.oms.spi.vo.v2.response.Response;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.tools.builder.WinitToolsProductFieldBuilder;
import com.winit.openapi.tools.validator.WinitToolsProductFieldValidator;
import com.winit.pms.spi.v2.instance.pscInstance.ProductInstanceService;
import com.winit.pms.spi.v2.instance.pscInstance.command.ProductInstanceByDeliveryModeCommand;
import com.winit.pms.spi.v2.instance.pscInstance.vo.ProductInstance;
import com.winit.ups.spi.warehouse.WarehouseService;
import com.winit.ups.spi.warehouse.command.QueryWarhouseByIdCommand;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

/**
 * winit接口:winit产品相关接口
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * bing.gu 	1.0  		2017年6月26日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/winit/tools/product")
public class WinitToolsProductController extends BaseController {

    @Resource
    private WinitProductRecommendService winitProductRecommendService;
    @Resource
    private ProductInstanceService       productInstanceService;
    @Resource
    private WarehouseService             upsWarehouseService;

    /**
     * winit产品校验推荐接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/recommend")
    public String recommend(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        ProductRecommendRequestParams requestParams = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            WinitToolsProductFieldValidator.recommendRequesParamsValidate(json);
            requestParams = WinitToolsProductFieldBuilder.buildRecommendRequestParams(json);
            // 如果仓库编码是纯数字,就有可能是老接口适配过来的仓库ID,调用ups接口适配到仓库编码
            if(isNumber(requestParams.getWarehouseCode())){
                QueryWarhouseByIdCommand houseCommand = new QueryWarhouseByIdCommand();
                houseCommand.setWarehouseId(Long.valueOf(requestParams.getWarehouseCode()));
                WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseById(houseCommand);
                if(null==warehouseVo){
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "warehouseCode");
                }
                requestParams.setWarehouseCode(warehouseVo.getCode());
            }
            // 如果产品编码是纯数字,就有可能是老接口适配过来的派送方式ID,调用PMS2接口适配到产品编码
            if (isNumber(requestParams.getWinitProductCode())) {
                ProductInstanceByDeliveryModeCommand command = new ProductInstanceByDeliveryModeCommand();
                command.setDeliveryMode(requestParams.getWinitProductCode());
                ProductInstance instance = productInstanceService.getProductByDeliveryMode(command);
                if (null == instance) {
                    throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "winitProductCode");
                }
                requestParams.setWinitProductCode(instance.getCode());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 组装command
        ProductRecommendCommand command = new ProductRecommendCommand();
        command.setCtx(CommandContext.getContext());
        command.setRequestParams(requestParams);
        // 调用接口
        ProductRecommendProductResult result = winitProductRecommendService.recommend(command);
        if (null != result) {
            responseMsg.setData(WinitToolsProductFieldBuilder.buildRecommendResult(result));
        }
        return SUCCESS;
    }

    /**
     * winit产品校验推荐接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/egdValidate")
    public String egdValidate(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        // 组装command
        BatchEGDValidateCommand command = new BatchEGDValidateCommand();
        command.setCtx(CommandContext.getContext());
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            WinitToolsProductFieldValidator.egdValidateParamsValidate(json);
            JSONArray jsonArray = json.getJSONArray("outboundOrderNos");
            List<String> outboundOrderNos = new ArrayList<String>();
            for (Object object : jsonArray) {
                outboundOrderNos.add(object.toString());
            }
            command.setOutboundOrderNos(outboundOrderNos);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 调用接口
        Response result = winitProductRecommendService.batchEGDValidate(command);
        if (null != result) {
            responseMsg.setData(WinitToolsProductFieldBuilder.buildEGDValidatResult(result));
        }
        return SUCCESS;
    }

    private boolean isNumber(String numStr) {
        if(StringUtils.isBlank(numStr)){
            return false;
        }
        try {
            Integer.valueOf(numStr);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
